<?php

/**
 * App
 *
 * @package App
 * @subpackage page
 */
require_once 'App.php';

/**
 * * App_Url
 *
 * <pre>URL管理クラス
 * </pre>
 *
 * @package     App
 * @subpackage  page
 * @author      $Author: moriwaki $
 * @version     $Id: 2008-10-01 moriwaki $
 */
class App_Url
{

    /**
     * uri
     *
     * @var string
     */
    var $uri = null;

    /**
     * query string
     *
     * @var array
     */
    var $params = array();

    /**
     * App_Url
     *
     * @param string $uri 
     * @param array $params
     * @return void
     */
    function App_Url($uri, $params=array())
    {
        $this->uri = $uri;
        $this->params = $params;
    }

    /**
     * get
     *
     * @return $url
     */
    function getUrl()
    {
        $url = $this->uri;
        $params = $this->params;
        $i = 0;
        foreach($params as $key => $value){
            if (is_array($value)){
                for ($j=0;$j<count($value);$j++){
                    if ($i == 0){
                        $url .= '?';
                    }else{
                        $url .= '&';
                    }
                    $url .= $key.'[]='.urlencode($value[$j]);
                    $i++;
                }
            }else{
                if ($i == 0){
                    $url .= '?';
                }else{
                    $url .= '&';
                }
                $url .= $key.'='.urlencode($value);
                $i++;
            }
        }
        return $url;
    }

    /**
     * set para
     *
     * @param string $uri
     * @return void
     */
    function setUri($uri)
    {
        $this->uri = $uri;
    }

    /**
     * set para
     *
     * @param string パラメータ名
     * @param string 値
     * @return $url
     */
    function setParam($key,$value)
    {
        $this->params[$key] = $value;
    }

    /**
     * remove param
     *
     * @param string パラメータ名
     * @return $url
     */
    function removeQuery($remove_params)
    {
        $url = $this->uri;

        if(!is_array($remove_params)){
            $remove_params = array($remove_params);
        }

        list($base_url, $query) = explode('?', $url, 2);

        $result = $url;

        if($query != ''){
            $query_array = explode('&', $query);
            $new_query = '';

            foreach($query_array as $param){
                list($k, $v) = explode('=', $param, 2);

                if(!in_array($k, $remove_params)){
                    if($new_query != ''){
                        $new_query .= '&';
                    }
                    $new_query .= $k.'='.$v;
                }
            }

            $result = $base_url;
            if($new_query != ''){
                $result .= '?'.$new_query;
            }
        }

        return $result;
    }
}
